package challenge;

import java.io.*;
import java.util.*;
import java.net.*;

public class WhatURL {
	
	/**入力したURLのページ取得
	 * 写経によるものを改変
	 * @throws MalformedURLException
	 * @throws ProtocolException
	 * @throws IOException
	 */
	public static void getpage()
		throws MalformedURLException,ProtocolException,IOException{
		BufferedReader br;
		br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("URLを入力してください");
		String urlname = br.readLine();
		URL url = new URL(urlname);
		br.close();
		
		HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
//		urlcon.setRequestMethod("GET");
//		urlcon.setInstanceFollowRedirects(false);
//		urlcon.setRequestProperty("", "");
		
		urlcon.connect();
		
		Map headers = urlcon.getHeaderFields();
		Iterator it = headers.keySet().iterator();
		System.out.println("レスポンスヘッダ");
		while(it.hasNext()){
			String key = (String)it.next();
			System.out.println(" "+key+" : "+headers.get(key));
		}
		
		System.out.println(""+urlcon.getResponseCode()+""+urlcon.getResponseMessage());
		System.out.println("\n---ボディ---");
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
		while(true){
			String line = reader.readLine();
			if(line==null){
				break;
			}
			System.out.println(line);
		}
		
		urlcon.disconnect();
		
	}
	
	/**最終更新日修得メソッド
	 * 
	 * @throws MalformedURLException
	 * @throws ProtocolException
	 * @throws IOException
	 */
	public static String getModified()
		throws MalformedURLException,ProtocolException,IOException{
		BufferedReader br;
		br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("URLを入力してください");
		String urlname = br.readLine();
		URL url = new URL(urlname);
		br.close();
		
		HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
		urlcon.connect();
		
		Map headers = urlcon.getHeaderFields();
		Iterator it = headers.keySet().iterator();
		
		String modified = "Last-Modified";
		String ret = "最終更新日："+headers.get(modified);
		urlcon.disconnect();
		
		return ret;
	}
	
	
	public static void main(String args[])
		throws MalformedURLException, ProtocolException, IOException{
		getpage();
	}
}
